package com.quanyan.comment.utils;


import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by admin on 2015/7/9.
 */
public class BusinessUtil {
    /** wi =2(n-1)(mod 11);加权因子   */
    public final static int[] wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    /** 校验码  */
    public final static int[] vi = { 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 };
    public static int[] ai = new int[18];

    /**
     * 简单校验身份证
     * @param idcard
     * @return
     */
    public static boolean verifyIDCard(String idcard) {
        if (idcard.length() == 15) {
            idcard = uptoeighteen(idcard);
        }
        if (idcard.length() != 18) {
            return false;
        }
        String verify = idcard.substring(17, 18);
        // 鉴于有的特殊身份证校验位有错，去掉校验位验证
		/*
		 * if (verify.equals(getVerify(idcard))) { return true; }
		 */
        // 前17位为数字
        if (!isNumeric(idcard.substring(0, 17))) {
            return false;
        }
        // 7-15为日期格式
        if (!isDate(idcard.substring(6, 14))) {
            return false;
        }
        // 最后一位是数字或者'x','X'
        return Character.isDigit(verify.charAt(0))
                || "X".equals(verify.toUpperCase());
    }

    // 15位转18位
    private static String uptoeighteen(String fifteen) {
        int i,j,s=0;
        String eighteen =null;
        eighteen = fifteen;
        eighteen =eighteen.substring(0,6)+"19"+eighteen.substring(6,fifteen.length());
        for ( i=0;i<eighteen.length() ;i++ )
        {
            j= Integer.parseInt(eighteen.substring(i,i+1)) * wi[i];
            s=s+j;
        }
        s = s % 11;
        eighteen=eighteen+vi[s];
        return eighteen;
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        return isNum.matches();
    }


    /**
     * 判断字符串是否为日期
     * @param str
     * @return
     */
    private static boolean isDate(String str){
        Pattern pattern = Pattern
                .compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
        Matcher m = pattern.matcher(str);
        return m.matches();

    }

    public static String encodeStr(String str) {
//        if (StringUtils.isNotEmpty(str)){
//            try {
//                Util.log("before" + str);
//                str = new String(str.getBytes("ISO-8859-1"),"UTF-8");
//                Util.log("after"+str);
//                return str;
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//                return null;
//            }
//        }
        return str;
    }

    public static File writeToTempFile(InputStream in, File out, Long expectedFileSize) throws IOException {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(out);

            IOUtils.copy(in, fos);

            if (expectedFileSize != null) {
                Long bytesWrittenToDisk = out.length();
                if (!expectedFileSize.equals(bytesWrittenToDisk)) {
                    throw new IOException(
                            String.format(
                                    "Unexpected file size mismatch. Actual bytes %s. Expected bytes %s.",
                                    bytesWrittenToDisk, expectedFileSize));
                }
            }

            return out;
        } catch (Exception e) {
            throw new IOException(e);
        } finally {
            IOUtils.closeQuietly(fos);
        }
    }

    public static List<Integer> getArraysByStr(String str){
        if (StringUtils.isNotBlank(str)){
            String[] tmp = StringUtils.split(str, ",");
            if (null != tmp && tmp.length > 0){
                List<Integer> result = new ArrayList<Integer>();
                for (int i=0; i<tmp.length; i++){
                    result.add(Integer.parseInt(tmp[i]));
                }
                return result;
            }
        }
        return null;
    }

    public static String listToString(List<?> stringList){
        if (stringList==null) {
            return null;
        }
        StringBuilder result=new StringBuilder();
        boolean flag=false;
        for (Object string : stringList) {
            if (flag) {
                result.append(",");
            }else {
                flag=true;
            }
            result.append(string);
        }
        return result.toString();
    }

    /**
     * 把毫秒转化成日期
     * @param dateFormat(日期格式，例如：MM/ dd/yyyy HH:mm:ss)
     * @param millSec(毫秒数)
     * @return
     */
    public String transferLongToDate(String dateFormat,Long millSec){
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        Date date= new Date(millSec);
        return sdf.format(date);
    }

    /**
     * 对一个list进行分页
     */
    public static List<?> pageList(List list, Integer pageSize, Integer pageNum){
        if (pageNum <1){
            pageNum =1;
        }
        if (pageSize <1){
            pageSize = 10;
        }
        List<?> result = null;
        if (list.size() > 0){
            int pageCount = 0;
            int pageResidue = list.size() % pageSize;
            if (pageResidue == 0) {
                pageCount = list.size() / pageSize;
            } else {
                pageCount = (list.size() / pageSize) + 1;
            }
            if (pageNum <= pageCount) {
                if (pageCount == pageNum && pageResidue > 0) {
                    result = list.subList((pageNum - 1) * pageSize, (pageNum - 1) * pageSize + pageResidue);
                } else {
                    result = list.subList((pageNum - 1) * pageSize, pageSize * pageNum);
                }
            }
        }
        return result;
    }
}
